import os
import subprocess
import time

import cv2 as cv2
import numpy as np


def filter_pictures(filename):
    return list(filter(lambda x: x.endswith('.jpg'), filename))


def delete_images(savedirname) -> bool:
    files = os.listdir(savedirname)
    try:
        for i, file in enumerate(files):
            print(file)
            if file.endswith('.jpg'):
                print(f"\rRemoving image.... {1 + i}...", end='')
                os.remove(os.path.join(savedirname, file))
            return True
    except Exception as e:
        print(e)


def save_images(imgs, savedirname, type='jpg') -> bool:
    if savedirname is None:
        return print("save path is None")
    try:
        for i, img in enumerate(imgs):
            print(f"\rWriting image.... {1 + i}...", end='')
            cv2.imwrite(savedirname + f'/{i}.jpg', img)
        return True
    except Exception as e:
        print(e)


def video2images(video_name, size, savedirname) -> bool:
    imgs = []
    cap = cv2.VideoCapture(video_name)
    while cap.isOpened():
        ret, frame = cap.read()
        if ret:
            print(f"\rReading video.... {1 + len(imgs)}...", end='')
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            img = cv2.resize(gray, size, interpolation=cv2.INTER_AREA)
            # img = cv2.Canny(img, 9, 40)
            # lap_5 = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]])
            lap_9 = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])
            img = cv2.filter2D(img, cv2.CV_8U, lap_9)
            imgs.append(img)
        else:
            break
    cap.release()
    return save_images(imgs, savedirname)


def image2chars(img) -> list:
    res = []
    # 用于生成字符画的像素，越往后视觉上越明显
    pixels = r" .,-'`:1*bdfhjlnprtvxz>)/}]24680BDFHJLNPRTVX%@$"

    percents = img / 255
    indexes = (percents * (len(pixels) - 1)).astype(np.int32)
    height, width = img.shape
    for row in range(height):
        line = ""
        for col in range(width):
            index = indexes[row][col]
            line += pixels[index]
        res.append(line)
    return res


def play_video(video_chars):
    chars = []
    chars = '\n'.join(video_chars)
    subprocess.run("cls", shell=True)
    print(chars)
    time.sleep(0.01)


minth = 50
maxth = 100


def test_canny():

    def call_callback_min(x):
        global minth
        minth = x

    def call_callback_max(x):
        global maxth
        maxth = x

    cv2.namedWindow('video')
    cv2.createTrackbar('min_callback', 'video', 0, 255, call_callback_min)
    cv2.createTrackbar('max_callback', 'video', 0, 255, call_callback_max)
    cap = cv2.VideoCapture('./vedio/486797170-1-80.flv')
    while cap.isOpened():
        ret, frame = cap.read()
        if ret:
            frame = cv2.resize(frame, dsize=None, fx=0.5, fy=0.5)
            frame = cv2.Canny(frame, minth, maxth)
            cv2.imshow('video', frame)
            if cv2.waitKey(20) & 0xff == 27:
                break
        else:
            break
    cap.release()


if __name__ == "__main__":
    video2images('./vedio/486797170-1-80.flv', (176, 40), './imgs/raw')
    # del_image('./imgs/raw')
    files = filter_pictures(os.listdir('./imgs/raw'))
    for i in range(len(files)):
        img = cv2.imread(f'./imgs/raw/{i}.jpg', 0)
        chars = image2chars(img)
        play_video(chars)